package manage.run;

import api.service.ApiConvertDataService;
import m.appserver.ServerHandler;
import m.common.model.HostInfo;
import m.common.model.util.ModelUpdateUtil;
import m.common.service.HostInfoService;
import m.system.RuntimeData;
import m.system.SystemTaskRun;
import m.system.db.TransactionManager;
import m.system.util.DateUtil;
import m.system.util.GenerateID;
import m.system.util.NumberUtil;
import m.system.util.SystemUtil;
import manage.model.ServerHost;
import manage.model.ServerRequest;
import manage.model.ServerRequestDetail;
import manage.model.ServerSetting;
import manage.service.ServerSettingService;

import java.util.*;

public class ServerTask extends SystemTaskRun {
	

	private static Date lastDate;
	@Override
	public void run(boolean isMain) throws Exception {//定时器为每分钟0秒执行
		SystemUtil.println("服务器时间：",DateUtil.format(new Date(),DateUtil.YYYY_MM_DD_HH_MM_SS)," \t ",isMain);
		//数据转换执行
		if(isMain) ApiConvertDataService.timeExecute();
		if(null==lastDate) lastDate=HostInfoService.getCurrentHost().getCreateDate();
		TransactionManager tm=new TransactionManager();
		Map<String,ServerRequest> requestMap=null;
		Map<String,List<ServerRequestDetail>> detailMap=null;
		try {
			ServerSettingService service=RuntimeData.getService(ServerSettingService.class);
			ServerSetting setting = service.getUniqueModel();
			if(!setting.getRequestMonitor().equals("Y")) return ;
			Date now=new Date();
			int minute=DateUtil.get(now, Calendar.MINUTE);
			boolean tmp=false;
			switch (setting.getRecordDuration()) {
				case "A":
					tmp = minute % 5 == 0;
					break;
				case "B":
					tmp = minute % 10 == 0;
					break;
				case "C":
					tmp = minute % 20 == 0;
					break;
				case "D":
					tmp = minute % 30 == 0;
					break;
				case "E":
					tmp = minute % 60 == 0;
					break;
				case "Z":
					tmp = true;//每分钟执行
					break;
			}
			if(!tmp) return ;
			SystemUtil.println("ServerTask start----------------");
			tm.begin();
			Date td=null;
			if(setting.getSaveDuration().equals("A")) td=DateUtil.getAddDate(now, -30);
			if(setting.getSaveDuration().equals("B")) td=DateUtil.getAddDate(now, -90);
			if(setting.getSaveDuration().equals("C")) td=DateUtil.getAddDate(now, -180);
			if(setting.getSaveDuration().equals("D")) td=DateUtil.getAddDate(now, -360);
			if(null!=td) service.deleteRecord(td);//删除
			HostInfoService.resetCurrentHostOtherInfo();
			HostInfo host=HostInfoService.getCurrentHost();
			ServerHost sh=new ServerHost();
			sh.setOid(GenerateID.generatePrimaryKey());
			
			requestMap=ServerFilter.getRequestMap();
			detailMap=ServerFilter.getDetailMap();
			List<ServerRequest> srlist= new ArrayList<>();
			List<ServerRequestDetail> srdlist= new ArrayList<>();
			int total=0;
			double access1=0.0;
			for(String key : requestMap.keySet()) {
				ServerRequest sr=requestMap.get(key);
				sr.setOid(GenerateID.generatePrimaryKey());
				sr.setContextPath(null!=sr.getContextPath()?(sr.getContextPath().length()>200?sr.getContextPath().substring(0,200):sr.getContextPath()):"");
				sr.setServerHost(sh);
				List<ServerRequestDetail> ds=detailMap.get(key);
				if(null==ds){
					sr.setTotal(0);
				}else {
					sr.setTotal(ds.size());
					for (ServerRequestDetail d : ds) {
						sr.setAccessLong(NumberUtil.round(sr.getAccessLong() + d.getAccessLong() / 1000.0));
						d.setServerRequest(sr);
						srdlist.add(d);
					}
				}
				sr.setAvgLong(NumberUtil.round(sr.getAccessLong()/sr.getTotal()));
				total+=sr.getTotal();
				access1+=sr.getAccessLong();
				srlist.add(sr);
			}
			sh.setIpport(host.getIpport());
			sh.setServerName(host.getServerName());
			sh.setServerPort(host.getServerPort());
			sh.setLogDate(DateUtil.add(lastDate, Calendar.SECOND, 1));
			sh.setEndDate(now);
			lastDate=now;
			sh.setInvalidRequest(ServerHandler.invalidRequestCount);
			ServerHandler.invalidRequestCount=0;
			sh.setTotal(total);
			sh.setAccessLong(NumberUtil.round(access1));
			sh.setAvgLong(sh.getTotal()==0.0?0.0:NumberUtil.round(sh.getAccessLong()/sh.getTotal()));
			sh.setTotalMemory(host.getTotalMemory());
			sh.setFreeMemory(host.getFreeMemory());
			sh.setMaxMemory(host.getMaxMemory());
			sh.setDbUseLinkNum(host.getDbUseLinkNum());
			sh.setDbMaxLinkNum(host.getDbMaxLinkNum());
			ModelUpdateUtil.insertModel(sh);
			ModelUpdateUtil.insertModels(srlist.toArray(new ServerRequest[] {}));
			ModelUpdateUtil.insertModels(srdlist.toArray(new ServerRequestDetail[] {}));
			SystemUtil.println("ServerTask end----------------");
			tm.commit();
		} catch (Exception e) {
			tm.rollback();
			throw e;
		} finally {
			if(null!=requestMap)
				requestMap.clear();
			if(null!=detailMap)
				detailMap.clear();
		}
	}

}
